package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.dto.AllCate;
import com.itheima.ydd.dto.ArticleDto;
import com.itheima.ydd.dto.NewUser;
import com.itheima.ydd.dto.UserDto;
import com.itheima.ydd.entity.SysConfig;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.mapper.IndexMapper;
import com.itheima.ydd.service.ISysConfigService;
import com.itheima.ydd.service.ISysUserService;
import com.itheima.ydd.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/index")
@Slf4j
@CrossOrigin
public class SysIndexController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private IndexMapper indexMapper;

    @PostMapping("/login")
    public R login(@RequestBody SysUser sysUser) {
        log.info("登陆用户：{}", sysUser.toString());

        String loginName = sysUser.getLoginName();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getLoginName, loginName);
        SysUser one = sysUserService.getOne(wrapper);

        if (one == null) {
            return R.error("账号不存在");
        } else if (one.getStatus() == 0) {
            return R.error("账号已禁用");
        }

        String password = sysUser.getPassword();
        if (one.getPassword().equals(generatePassword(password))) {
            //把用户id 加密进token里

            // 生成token信息
            Map retMap = new HashMap();
            Map tokenMap = new HashMap<>();
            String roleId = one.getRoleId()
                    .replace("[", "")
                    .replace("]", "")
                    .replace("\"", "");

            tokenMap.put("userId", one.getId());
            tokenMap.put("roleId", roleId);

            String token = JwtUtils.getToken(tokenMap);
            retMap.put("token", token);
            return R.success("token", JwtUtils.getToken(tokenMap));
        }
        return R.error("密码错误");

    }


    @GetMapping("/getConfig")
    public R systemConfig() {
        LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysConfig::getTabValue, "system");
        List<SysConfig> sysConfigs = sysConfigService.list(wrapper);

        HashMap<String, String> map = new HashMap<>();
        for (SysConfig sysConfig : sysConfigs) {
            map.put(sysConfig.getAttrKey(), sysConfig.getAttrValue());
        }

        return new R(map, "", 0);

    }

    @PostMapping("/profile")
    public R profile(HttpServletRequest request) {
        String token = request.getHeader("x-token");

        Claims claims = JwtUtils.getClaims(token);
//        Long userId = Long.valueOf((String) claims.get("userId"));
        String userId = UserHolder.getUserId();

        log.info("用户id:{}", userId);
        return sysUserService.profile(userId);
    }

    /**
     * md5加密
     *
     * @param password 密码
     */
    private String generatePassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }

    /**
     * 主页图表数据展示
     * @return
     */
    @GetMapping("/baseInfo")
    public ResultData baseInfo(){
        //创建map集合封装对象
        HashMap data = new HashMap<>();
        //查询管理员数量admin_num
        int admin_num = sysUserService.count();
        data.put("admin_num",admin_num);
        //查询广告位advpos_num
        int advpos_num = indexMapper.advpos_num();
        data.put("advpos_num",advpos_num);
        //查询广告图advimg_num
        int advimg_num = indexMapper.advimg_num();
        data.put("advimg_num",advimg_num);
        //查询文章总数article_num
        int article_num = indexMapper.article_num();
        data.put("article_num",article_num);
        //查询标签总数tag_num
        int tag_num = indexMapper.tag_num();
        data.put("tag_num",tag_num);
        //查询文章分类数cate_num
        int cate_num = indexMapper.cate_num();
        data.put("cate_num",cate_num);
        //查询用户总数，
        UserDto user = new UserDto();
        List<HashMap<Integer, Long>> map = indexMapper.user();
        Long man = map.get(0).get("number");
        Long woman = map.get(1).get("number");
        user.setUser_man(man);
        user.setUser_woman(woman);
        user.setTotal(man+woman);
        data.put("user",user);
        //查询文件分类各类文件相应个数all_cate
        List<AllCate> allCates = indexMapper.all_cate();
        data.put("all_cate",allCates);
        //查询最新用户注册详情(7位用户)new_user
        List<NewUser> newUsers = indexMapper.new_user();
        data.put("new_user",newUsers);
        //查询点击率最多的7个文章hot_article;
        List<ArticleDto> articleDtos = indexMapper.hot_article();
        data.put("hot_article",articleDtos);

        return ResultData.ok("",data);

    }
}
